/*
 *  Licensed to the Apache Software Foundation (ASF) under one
 *  or more contributor license agreements.  See the NOTICE file
 *  distributed with this work for additional information
 *  regarding copyright ownership.  The ASF licenses this file
 *  to you under the Apache License, Version 2.0 (the
 *  "License"); you may not use this file except in compliance
 *  with the License.  You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing,
 *  software distributed under the License is distributed on an
 *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 *  KIND, either express or implied.  See the License for the
 *  specific language governing permissions and limitations
 *  under the License.
 *
 */
package com.sunchangming.uniqname;

import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolEncoderAdapter;
import org.apache.mina.filter.codec.ProtocolEncoderOutput;

import com.google.protobuf.CodedOutputStream;
import com.google.protobuf.Message;


public class ProtobufEncoder extends ProtocolEncoderAdapter {

	/**
	 * Creates the instance of the encoder.
	 */
	protected ProtobufEncoder() {
	}

	/**
	 * Encodes the protobuf {@link Message} provided into the wire format.
	 * 
	 * @param session
	 *            The session (not used).
	 * @param message
	 *            The protobuf {@link Message}.
	 * @param out
	 *            The encoder output used to write buffer into.
	 */
	@Override
	public void encode(IoSession session, Object message, ProtocolEncoderOutput out) throws Exception {
		Res res = (Res) message;
		int size = res.msg.getSerializedSize();
		IoBuffer buffer = IoBuffer.allocate(size + 2 + 4);
		int type = res.methodid;
		int length = size + CodedOutputStream.computeInt32SizeNoTag(type);
		if (length > 255 * 255) {
			throw new RuntimeException("包太大");
		}
		CodedOutputStream cos = CodedOutputStream.newInstance(buffer.asOutputStream());
		cos.writeRawByte(length >> 8);
		cos.writeRawByte(length & 255);
		cos.writeInt32NoTag(type);
		res.msg.writeTo(cos);
		cos.flush();
		buffer.flip();
		out.write(buffer);
	}

}